/*
* 菜单管理模块
*/
const express = require('express');
const router = express.Router();
// 引入数据库
const db = require("../../config/db");
// 引入时间包
const moment = require("moment");
// 引入方法库
const { toCamelCase, toUnderlineCase, verifyToken, recursionGenerateTree} = require("../../config/utils");
// 引入日志
const log = require("../log");
//m密码使用md5模块进行的加密
const md5 = require('md5');

// 获取所有菜单列表
router.get("/list", async (req, res) => {
    console.log("===========获取菜单列表接口============");
    // 获取参数
    let { menuName, status,  } = req.query;
    // 拼接sql语句
    let sql = "select * from sys_menu";
    let sql_where = ` where 1=1`;
    if(menuName){
        sql_where += ` and menu_name like '%${menuName}%'`;
    }
    if(status){
        sql_where += ` and status = '${status}'`;
    }
    if( menuName || status ){
        sql += sql_where;
    }
    
    // 查询数据库
    db.query("查询菜单列表", sql, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询菜单列表失败", data: err});
            return;
        }
        if(result.length > 0){
            // 变量Json数组key转成下划线第一个大写
            result = result.map(item => {
               return toCamelCase(item)
           })
           res.send({code: 200, msg: "查询菜单列表成功", data: result, });
       }else{
           res.send({code: 200, msg: "查询菜单列表成功", data: [], total: 0});
       }
    })
})

// 新增菜单列表
router.post("/", (req, res)=>{
    console.log("===========新增菜单列表接口============");
    // 获取参数
    let { menuName, menuType, orderNum, parentId, path, perms, icon, component, query, isFrame, isCache, visible, status} = req.body;
    // 获取创建人
    let {username} = verifyToken(req.headers.authorization);
    // 获取创建时间
    let createTime = moment().format("YYYY-MM-DD HH:mm:ss");
    // 判断菜单名称是否重复
    db.query("查询菜单名称是否重复", `select * from sys_menu where menu_name = '${menuName}'`, (err, sql_check_result)=>{
        if(err){
            res.send({code: 500, msg: "查询菜单名称是否重复失败", data: err});
            return;
        }
        if(sql_check_result.length > 0){
            res.send({code: 500, msg: "菜单名称已存在"});
            return;
        }
        // 插入数据库
        let sql = `insert into sys_menu (menu_name, menu_type, order_num, parent_id, path, perms, icon, component, query, 
            is_frame, is_cache, visible, status, create_by, create_time)
        values 
        ( '${menuName}', '${menuType}', '${orderNum}', '${parentId}', ${path ? "'"+path+"'" : null},  ${perms ? "'"+perms+"'" : null}, 
        ${icon ? "'"+icon+"'" : null}, ${component ? "'"+component+"'" : null}, ${query ? "'"+query+"'" : null}, 
        '${isFrame}', '${isCache}', '${visible}', '${status}', '${username}', '${createTime}')`;
        db.query("新增菜单列表", sql, (err, result)=>{
            if(err){
                res.send({code: 500, msg: "新增菜单列表失败", data: err});
                return;
            }
            if(result.affectedRows > 0){
                res.send({code: 200, msg: "新增菜单列表成功"});
            }else{
                res.send({code: 500, msg: "新增菜单列表失败"});
            }
        })
    })
})

// 查询单个菜单列表
router.get(/^\/(\d+)$/, (req, res) => {
    console.log("===========查询单个菜单列表接口，正则匹配============");
    // 获取参数
    let url_arr = req.url.split("/");
    const id = url_arr[url_arr.length - 1];
   
    db.query("查询单个菜单列表", `select * from sys_menu where menu_id = ${id}`, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询单个菜单列表失败", data: err});
            return;
        }
        if(result.length > 0){
            // 变量Json数组key转成下划线第一个大写
            result = result.map(item => {
                item.is_frame = item.is_frame + ''
                item.is_cache = item.is_cache + ''
                return toCamelCase(item)
            })
            res.send({code: 200, msg: "查询单个菜单列表成功", data: result[0]});
        }else{
            res.send({code: 500, msg: "查询单个菜单列表失败"});
        }
    })
})

// 修改菜单列表
router.put("/", (req, res)=>{
    console.log("===========修改菜单列表接口============");
    // 获取参数
    let { menuName, menuType, orderNum, parentId, path, perms, icon, component, query, isFrame, isCache, visible, status, menuId} = req.body;
    // 获取修改人
    let {username} = verifyToken(req.headers.authorization);
    // 获取修改时间
    let updateTime = moment().format("YYYY-MM-DD HH:mm:ss");
    // 查询菜单名称是否重复
    db.query("查询类型名称是否重复", `select * from sys_menu where menu_id != ${menuId} and menu_name = '${menuName}'`, (err, result)=>{
        if(err){
            res.send({code: 500, msg: "查询菜单名称是否重复失败", data: err});
            return;
        }
        if(result.length > 0){
            res.send({code: 500, msg: "菜单名称已存在", data: []});
            return;
        }
        // 修改菜单列表sql
        let sql = `update sys_menu set menu_name = '${menuName}', menu_type = '${menuType}', order_num = '${orderNum}', parent_id = '${parentId}',
        path = ${path ? "'"+path+"'" : null}, perms = ${perms ? "'"+perms+"'" : null},  icon =  ${icon ? "'"+icon+"'" : null}, 
        component = ${component ? "'"+component+"'" : null}, query = ${query ? "'"+query+"'" : null}, 
        is_frame = '${isFrame}', is_cache = '${isCache}', visible = '${visible}', status = '${status}',
        update_by = '${username}', update_time = '${updateTime}'
        where menu_id = ${menuId}`;
        db.query("修改菜单列表", sql, (err, result)=>{
            if(err){
                res.send({code: 500, msg: "修改菜单列表失败", data: err});
                return;
            }
            if(result.affectedRows > 0){
                res.send({code: 200, msg: "修改菜单列表成功", data: []});
            }else{
                res.send({code: 500, msg: "修改菜单列表失败", data: []});
            }
        })
    })
})

// 删除菜单列表
router.delete('/:menu_id', (req, res) => {
    console.log("===========删除菜单列表接口============");
    // 判断有没有权限(只判断账号admin，和后续优化)
    let {username} = verifyToken(req.headers.authorization)
    if(username != 'admin') {
        res.send({code: 400, msg: '没有权限，请联系管理员授权'})
        return
    }
    // 获取参数
    let {menu_id} = req.params;
    // 查询是否存在子菜单
    db.query("查询是否存在子菜单", `select * from sys_menu where parent_id = '${menu_id}'`, (err, result) => {
        if (err) {
            res.send({code: 500, msg: '查询是否存在子菜单失败'})
            return
        }
        if(result.length > 0) {
            res.send({code: 500, msg: '存在子菜单，无法删除，请先删除子菜单'})
            return
        }
        // 删除数据库
        db.query("删除菜单列表", `delete from sys_menu where menu_id = '${menu_id}'`, (err, result) => {
            if (err) {
                res.send({code: 500, msg: '删除菜单列表失败'})
                return
            }
            if(result.affectedRows > 0) {
                res.send({ code: 200,msg: '删除成功', data: result })
            }else {
                res.send({ code: 500, msg: '删除失败' })
            }
        })
    })
})

// 查询菜单列表下拉树结构接口
router.get('/treeselect', (req, res) => {
    console.log("===========查询菜单列表下拉树结构接口============");
    // 查询数据库
    db.query("查询菜单列表下拉树结构接口", `select menu_id as id, menu_name as label, parent_id as pid  from sys_menu`, (err, result) => {
        if (err) { 
            res.send({code: 500, msg: '查询菜单列表下拉树结构接口失败'}) 
            return
        }
        if(result.length > 0) {
            // 生成树结构递归
            result = recursionGenerateTree(0, result)
        }
        res.send({
            code: 200,
            msg: '测试数据',
            data: result,
        })
    })
   
})

// 根据角色ID查询菜单下拉树结构
router.get('/roleMenuTreeselect/:roleId', (req, res) => {
    console.log("===========根据角色ID查询菜单下拉树结构============");
    // 获取参数
    let { roleId } = req.params;
    // 联合查询，根据角色id查询菜单id，再根据菜单id查询信息
    let sql_union = `select menu_id as id, menu_name as label, parent_id as pid  from sys_menu 
    where menu_id in (select menu_id from sys_role_menu where role_id = ${roleId})`;
    // 查询数据库
    db.query("根据角色ID查询菜单下拉树结构", sql_union, (err, result) => {
        if (err) { 
            res.send({code: 500, msg: '根据角色ID查询菜单下拉树结构失败'}) 
            return
        }
        if(result.length > 0) {
            // 生成树结构递归
            result = recursionGenerateTree(0, result)
            res.send({ code: 200, msg: '根据角色ID查询菜单下拉树结构成功', menus: result })
        }else{
            res.send({ code: 200, msg: '根据角色ID查询菜单下拉树结构成功', menus: [] })
        }
    })
})


module.exports = router;
